package random.fox.p2p.pathview;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import flow.Flow;
import flow.path.Path;
import flow.path.PathContainer;
import flow.path.PathContext;
import flow.path.PathContextFactory;

import static flow.Flow.Direction.REPLACE;

/**
 * Created by wq on 15/3/15.
 */
public class IndexPathContainer extends PathContainer {

    private final PathContextFactory contextFactory;

    public IndexPathContainer(int tagKey, PathContextFactory contextFactory) {
        super(tagKey);
        this.contextFactory = contextFactory;
    }

    @Override protected void performTraversal(final ViewGroup containerView,
                                              final TraversalState traversalState, final Flow.Direction direction,
                                              final Flow.TraversalCallback callback) {
        final PathContext context;
        final PathContext oldPath;
        if (containerView.getChildCount() > 0) {
            oldPath = PathContext.get(containerView.getChildAt(0).getContext());
        } else {
            oldPath = PathContext.root(containerView.getContext());
        }

        Path to = traversalState.toPath();

        ViewGroup newView;
        context = PathContext.create(oldPath, to, contextFactory);
        int layout = getLayout(to);
        newView = (ViewGroup) LayoutInflater.from(context)
                .cloneInContext(context)
                .inflate(layout, containerView, false);

        View fromView = null;
        if (traversalState.fromPath() != null) {
            fromView = containerView.getChildAt(0);
            traversalState.saveViewState(fromView);
        }
        traversalState.restoreViewState(newView);

        if (fromView == null || direction == REPLACE) {
            containerView.removeAllViews();
            containerView.addView(newView);
            oldPath.destroyNotIn(context, contextFactory);
            callback.onTraversalCompleted();
        } else {
            containerView.addView(newView);
            final View finalFromView = fromView;
//            TODO 暂时的注释掉
//            Utils.waitForMeasure(newView, new Utils.OnMeasuredCallback() {
//                @Override public void onMeasured(View view, int width, int height) {
//                    runAnimation(containerView, finalFromView, view, direction, new Flow.TraversalCallback() {
//                        @Override public void onTraversalCompleted() {
//                            containerView.removeView(finalFromView);
//                            oldPath.destroyNotIn(context, contextFactory);
//                            callback.onTraversalCompleted();
//                        }
//                    });
//                }
//            });
            containerView.removeView(finalFromView);
            oldPath.destroyNotIn(context, contextFactory);
            callback.onTraversalCompleted();
        }
    }
}
